import { defineStore } from 'pinia'
import { getToken, getUserInfo, setToken, setUserInfo, removeToken, removeUserInfo } from '@/utils/auth'
import { userApi } from '@/api'

// 用户状态存储
export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: getUserInfo() || {}
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    userName: (state) => state.userInfo.name || '',
    userRole: (state) => state.userInfo.role || ''
  },
  
  actions: {
    // 登录
    async login(loginForm) {
      try {
        // 模拟登录API调用
        // const res = await userApi.login(loginForm)
        
        if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
          const res = {
            token: 'mock-token-' + Date.now(),
            user: {
              id: 1,
              name: '管理员',
              role: 'admin'
            }
          }
          
          this.token = res.token
          this.userInfo = res.user
          
          setToken(res.token)
          setUserInfo(res.user)
          
          return Promise.resolve(res)
        }
        
        return Promise.reject(new Error('用户名或密码错误'))
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        if (this.token) {
          // 实际环境中应该从后端获取用户信息
          // const res = await userApi.getUserInfo()
          // this.userInfo = res
          // 这里直接返回已有的用户信息
          return Promise.resolve(this.userInfo)
        }
        return Promise.reject(new Error('未登录'))
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 登出
    logout() {
      this.token = ''
      this.userInfo = {}
      removeToken()
      removeUserInfo()
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
    }
  }
})

// 应用配置存储
export const useAppStore = defineStore('app', {
  state: () => ({
    sidebar: {
      opened: true,
      withoutAnimation: false
    },
    device: 'desktop',
    theme: localStorage.getItem('theme') || 'light'
  }),
  
  actions: {
    toggleSidebar() {
      this.sidebar.opened = !this.sidebar.opened
    },
    
    closeSidebar() {
      this.sidebar.opened = false
    },
    
    toggleDevice(device) {
      this.device = device
    },
    
    setTheme(theme) {
      this.theme = theme
      localStorage.setItem('theme', theme)
    }
  }
}) 